<script setup lang="ts">
  import { ref } from 'vue'
  import { NButton, NSpace } from 'naive-ui'
  const constraints = { audio: true, video: true }
  const video = ref<HTMLVideoElement | null>(null)
  let mediaTrack: MediaStream
  const start = () => {
    // 获取音频视频流
    navigator.mediaDevices
      .getUserMedia(constraints)
      .then((MediaStream) => {
        mediaTrack = MediaStream
        if (video?.value) {
          video.value.srcObject = MediaStream
          video.value.onloadedmetadata = function () {
            video?.value?.play?.()
          }
        }
      })
      .catch((e) => {
        console.warn(e, 'e')
      })
  }
  const stop = () => {
    video!.value!.srcObject = null
    mediaTrack?.getVideoTracks().forEach((track) => {
      track.stop()
    })
  }
</script>
<template>
  <div>
    <n-space>
      <n-button type="primary" @click="start()">start</n-button>
      <n-button type="info" @click="stop()">stop</n-button>
    </n-space>
    <video ref="video"></video>
  </div>
</template>
